const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');
const User = require('./User');
const BattleRoom = require('./BattleRoom');

class AnswerLog extends Model { }
AnswerLog.init(
  {
    id: {
      type: DataTypes.STRING(18),
      primaryKey: true,
      comment: '主键ID'
    },
    user_id: {
      type: DataTypes.STRING(18),
      allowNull: false,
      comment: '用户ID',
      references: {
        model: User,
        key: 'user_id'
      }
    },
    room_id: {
      type: DataTypes.STRING(18),
      allowNull: false,
      comment: '对战房间ID',
      references: {
        model: BattleRoom,
        key: 'room_id'
      }
    },
    answers: {
      type: DataTypes.JSON,
      allowNull: false,
      comment: '答题记录，格式：[{question_id: "xxx", answer: "A", time_used: 5000, is_correct: true}, ...]'
    },
    total_score: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '总得分'
    },
    total_time: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '总用时（毫秒）'
    },
    mode: {
      type: DataTypes.TINYINT,
      allowNull: false,
      comment: '答题模式：1-练习，2-对战'
    },
    create_time: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '创建时间'
    }
  },
  {
    sequelize,
    modelName: 'AnswerLog',
    tableName: 'answer_log',
    timestamps: false,
    comment: '答题记录表',
    indexes: [
      {
        fields: ['user_id']
      },
      {
        fields: ['room_id']
      },
      {
        fields: ['create_time']
      }
    ]
  }
);

// 建立关联关系
AnswerLog.belongsTo(User, {
  foreignKey: 'user_id',
  targetKey: 'user_id',
  as: 'user'
});

AnswerLog.belongsTo(BattleRoom, {
  foreignKey: 'room_id',
  targetKey: 'id',
  as: 'room'
});

module.exports = AnswerLog;